//
//  MainViewController.m
//  FaceRecognition
//
//  Created by Sylar on 2016/11/28.
//  Copyright © 2016年 Sylar. All rights reserved.
//

#import "MainViewController.h"
#import "FR_Par_HistoryViewController.h"
#import "FR_HistoryViewController.h"
#import "FR_ManagerInfoViewController.h"
#import "FR_PersonalViewController.h"
#import "FR_TeacherAcountViewController.h"
//#import "FR_StudentAccountViewController.h"
#import "FR_AdministratorAcountViewController.h"

#import "FR_AccountViewController.h"
#import "FR_History_Identity_ViewController.h"

#import "FR_HomeViewController.h"
#import "FR_MessageListViewController.h"

@interface MainViewController ()<UINavigationControllerDelegate>
{

    

    
    NSString *lasttype;//身份
    
    
    NSInteger haveClass;
    NSInteger havestudent;
    
    SYNavigationController *HomeNav;
    SYNavigationController *MessageNav;
    SYNavigationController *personalNav;
    
    FR_HomeViewController *homeViewController;
    FR_MessageListViewController *messageVC;
    FR_PersonalViewController *personalVC;
}

@end

@implementation MainViewController

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //if 使tabBarController中管理的viqewControllers都符合 UIRectEdgeNone
    if ([UIDevice currentDevice].systemVersion.floatValue >= 7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    [self getUserInfo];
    //[self judgeLoginState];
    
    lasttype =[NSString stringWithFormat:@"%d",[SYAccountTool ShareAccount].account.lasttype];
    
    //[self setupSubviews];
    
    self.selectedIndex = 1;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(switchRole:) name:@"switchrolenoti" object:nil];
    
    
    for (UITabBarItem *item in self.tabBar.items) {
        
        item.imageInsets = UIEdgeInsetsMake(-2, 0, 2, 0);
        
        [item setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                      [UIFont fontWithName:@"Helvetica" size:11.0], NSFontAttributeName, nil]
                            forState:UIControlStateNormal];
        
        [item setTitlePositionAdjustment:UIOffsetMake(-2, -2)];
        
    }
    

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



#pragma mark -搭建子视图控制器
- (void)setupSubviews
{
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
    
    /*
    if ([lasttype isEqualToString:@"1"]) {
        historyVC = [[FR_History_Identity_ViewController alloc]init];
        historyVC.isRootViewController = YES;
        historyNav = [[SYNavigationController alloc] initWithRootViewController:historyVC];
        historyNav.delegate = self;
        
        accountVC = [[FR_AccountViewController alloc]init];
        accountVC.isRootViewController = YES;
        AcountNav = [[SYNavigationController alloc]initWithRootViewController:accountVC];
        AcountNav.delegate = self;
        
    }else if ([lasttype isEqualToString:@"2"]) {
        par_historyVC = [[FR_Par_HistoryViewController alloc]init];
        par_historyVC.isRootViewController = YES;
        historyNav = [[SYNavigationController alloc] initWithRootViewController:par_historyVC];
        historyNav.delegate = self;
        
        par_AcountVC = [[FR_StudentAccountViewController alloc]init];
        par_AcountVC.isRootViewController = YES;
        AcountNav = [[SYNavigationController alloc]initWithRootViewController:par_AcountVC];
        AcountNav.delegate = self;
    }
     */
    

    
    homeViewController = [[FR_HomeViewController alloc]init];
    homeViewController.isRootViewController = YES;
    HomeNav = [[SYNavigationController alloc]initWithRootViewController:homeViewController];
    HomeNav.delegate = self;
    
    messageVC = [[FR_MessageListViewController alloc]init];
    messageVC.isRootViewController = YES;
    MessageNav = [[SYNavigationController alloc]initWithRootViewController:messageVC];
    MessageNav.delegate = self;
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.msgVC = messageVC;
    
    personalVC = [[FR_PersonalViewController alloc]init];
    personalVC.isRootViewController = YES;
    personalNav = [[SYNavigationController alloc] initWithRootViewController:personalVC];
    personalNav.delegate = self;
    
    //消息
    MessageNav.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"消息" image:[UIImage imageWithOriginalName:@"message_nor"] selectedImage:[UIImage imageWithOriginalName:@"message_press"]];
    [MessageNav.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} forState:UIControlStateNormal];
    MessageNav.tabBarItem.tag = 1;
    [self unSelectedTapTabBarItems:MessageNav.tabBarItem];
    [self selectedTapTabBarItems:MessageNav.tabBarItem];
    
    //主页
    HomeNav.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"主页" image:[UIImage imageWithOriginalName:@"home_nor"] selectedImage:[UIImage imageWithOriginalName:@"home_press"]];
    
    [HomeNav.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} forState:UIControlStateNormal];
    HomeNav.tabBarItem.tag = 1;
    [self unSelectedTapTabBarItems:HomeNav.tabBarItem];
    [self selectedTapTabBarItems:HomeNav.tabBarItem];
    
    
    //个人设置
    personalNav.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"我的" image:[UIImage imageWithOriginalName:@"presonal_nor"] selectedImage:[UIImage imageWithOriginalName:@"presonal_press"]];
    [personalNav.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} forState:UIControlStateNormal];
    personalNav.tabBarItem.tag = 2;
    [self unSelectedTapTabBarItems:personalNav.tabBarItem];
    [self selectedTapTabBarItems:personalNav.tabBarItem];
    
    
    self.viewControllers = @[MessageNav,HomeNav,personalNav];
}

-(void)unSelectedTapTabBarItems:(UITabBarItem *)tabBarItem
{
    [tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                        [UIFont systemFontOfSize:11], NSFontAttributeName,colorFromHex(@"999999"),NSForegroundColorAttributeName,
                                        nil] forState:UIControlStateNormal];
}


-(void)selectedTapTabBarItems:(UITabBarItem *)tabBarItem
{
    [tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                        [UIFont systemFontOfSize:11],
                                        NSFontAttributeName,DEFAULTCOLOR,NSForegroundColorAttributeName,
                                        nil] forState:UIControlStateSelected];
}


#pragma mark - Methods

-(void)switchRole:(NSNotification *)noti{
    
    self.selectedIndex = 1;
    self.tabBarController.tabBar.hidden = NO;
    
    [self changeHomeVC];
}

- (void)changeHomeVC {
    
    lasttype =[NSString stringWithFormat:@"%d",[SYAccountTool ShareAccount].account.lasttype];
    
    HomeNav = [self.viewControllers objectAtIndex:1];
    /*
    if ([lasttype isEqualToString:@"1"]) { //老师
        historyVC = [[FR_History_Identity_ViewController alloc]init];
        historyVC.isRootViewController = YES;
        [historyNav setViewControllers:@[historyVC] animated:NO];
        
//        if (schoolManager > 0) {
//            
//            admin_AcountVC = [[FR_AdministratorAcountViewController alloc]init];
//            admin_AcountVC.isRootViewController = YES;
//            [AcountNav setViewControllers:@[admin_AcountVC] animated:NO];
//            
//        }else
//        {
//            tea_AcountVC = [[FR_TeacherAcountViewController alloc]init];
//            tea_AcountVC.isRootViewController = YES;
//            [AcountNav setViewControllers:@[tea_AcountVC] animated:NO];
//        }
        
//        accountVC = [[FR_AccountViewController alloc]init];
//        accountVC.isRootViewController = YES;
//        [AcountNav setViewControllers:@[accountVC] animated:NO];
        
    }else{
        
        par_historyVC = [[FR_Par_HistoryViewController alloc]init];
        par_historyVC.isRootViewController = YES;
        [historyNav setViewControllers:@[par_historyVC] animated:NO];
        
//        par_AcountVC = [[FR_StudentAccountViewController alloc]init];
//        par_AcountVC.isRootViewController = YES;
//        [AcountNav setViewControllers:@[par_AcountVC] animated:NO];
    }
    */
    [self unSelectedTapTabBarItems:HomeNav.tabBarItem];
    [self selectedTapTabBarItems:HomeNav.tabBarItem];
    
    self.tabBarController.tabBar.hidden = NO;
    
}


-(void)judgeLoginState{
    
    
    NSMutableDictionary * paramDic = [[NSMutableDictionary alloc] initWithCapacity:0];
    [paramDic setObject:USERID forKey:@"teacherid"];
    [paramDic setObject:@"0" forKey:@"type"];
    [paramDic setObject:[SYAccountTool ShareAccount].account.scid forKey:@"scid"];
    
    [Utils Java_get:@"api/getTeacherClass" parameters:paramDic success:^(NSInteger recode, id jsonObject) {

        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        
        if (arr.count == 0) {  //没有班级
            
            self->haveClass = 0;
            
        }else if(arr.count > 0){ //有班级
            
            self->haveClass = 1;
            
        }
        
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary: [SyUserInfomation acquirePersonalImformationFromMemoryWithPersonID:USERID]];
        [dic setObject:[NSNumber numberWithInteger:haveClass] forKey:@"haveclass"];
        
        [SyUserInfomation personalImformationSaveWtih:dic];
        
        [[NSUserDefaults standardUserDefaults] setInteger:self->haveClass forKey:SYHaveClass];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
        [dict setObject:USERID forKey:@"parentid"];
        
        [Utils Java_get:@"api/getChildClass" parameters:dict success:^(NSInteger recode, id resposeJson) {

            NSDictionary * dict = (NSDictionary *)resposeJson;
            if ([[dict objectForKey:@"re_code"] integerValue]==0) {
                if ([[dict objectForKey:@"re_data"] count]>0) {
                    self->havestudent = 1;
                }else {
                    self->havestudent = 0;
                }
                
                
                int lasttyper = [SYAccountTool ShareAccount].account.lasttype;
                
                //上次登录是家长身份，此时家长身份被移除, 有老师身份
                if (lasttyper == 2 && havestudent == 0 && self->haveClass == 1) {
                    
                    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
                    [dict setObject:@"api_user_logintype" forKey:@"method"];
                    [dict setObject:USERID forKey:@"userid"];
                    [dict setObject:@"1" forKey:@"type"];
                    
                    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
                        
                        AppDelegate * appdelegate = CONSTAPPDELEGATE;
                        appdelegate.isChangeRole=@"yes";
                        
                        [self relogin];
                        
                    } failure:^(NSInteger recode, NSError * error){
                        
                    }];
                    
                    return;
                }
                
                if (lasttyper == 1 && havestudent == 1 && self->haveClass == 0 && [SYAccountTool ShareAccount].account.schoolnum == 0) {
                    
                    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
                    [dict setObject:@"api_user_logintype" forKey:@"method"];
                    [dict setObject:USERID forKey:@"userid"];
                    [dict setObject:@"2" forKey:@"type"];
                    
                    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
                        
                        AppDelegate * appdelegate = CONSTAPPDELEGATE;
                        appdelegate.isChangeRole=@"yes";
                        
                        [self relogin];
                        
                    } failure:^(NSInteger recode, NSError * error){
                       
                        [self showHint:error.localizedDescription];
                    }];
                    
                    return;
                }
                
                if (self->haveClass == 0 && self->havestudent == 0 && [SYAccountTool ShareAccount].account.schoolnum == 0) {

                    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
                    [dict setObject:@"api_user_logout" forKey:@"method"];
                    [dict setObject:USERID forKey:@"userid"];
                    if (lasttype) {
                        
                        [dict setObject:lasttype forKey:@"usertype"];
                    }
                    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
                        //NSDictionary *dict = (NSDictionary *)resposeJson;
                        //[Utils alertViewWithMessage:[dict objectForKey:@"re_info"]];
                        NSUserDefaults *udd=[NSUserDefaults standardUserDefaults];
                        [udd removeObjectForKey:@"studentID"];
                        [udd removeObjectForKey:SYStudentName];
                        [udd removeObjectForKey:@"userid"];
                        [udd synchronize];
                        AppDelegate * appdelegate = CONSTAPPDELEGATE;
                        appdelegate.studentId = nil;
                        appdelegate.myClasses = nil;
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                        
                        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
                        
                        
                    } failure:^(NSInteger recode, NSError * error){
                        
                    }];
                    
                    return;
                }
            }
            
            [self setupSubviews];
            self.selectedIndex = 1;
            
        } failure:^(NSInteger rocode, NSError * error){
            
        }];
        
    } failure:^(NSInteger recode, NSError *error) {
       
        [self showHint:error.localizedDescription];
    }];
    
}

- (void)getUserInfo {
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    
    [dict setObject:@"api_user_getinfobyid" forKey:@"method"];
    [dict setObject:USERID forKey:@"userid"];
    
    [Utils get:nil parameters:dict success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary * dict = (NSDictionary *)jsonObject;
        
        //判断是否开通平安家校
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:USERID forKey:@"userid"];
        [Utils Java_get:@"api/isOpenFace" parameters:param success:^(NSInteger recode, id jsonObject) {
            
            NSDictionary *jsonDict = (NSDictionary *)jsonObject;
            NSDictionary *re_data=[jsonDict objectForKey:@"re_data"];
            
            if ([[re_data objectForKey:@"openface"] integerValue] == 1) {
                
                NSMutableDictionary *personalImformation = [[NSMutableDictionary alloc]initWithDictionary: [dict objectForKey:@"re_data"]];
                if (personalImformation.count>0) {
                    
                    [personalImformation setObject:[NSString stringWithFormat:@"%d",[[re_data objectForKey:@"faceuserid"] intValue]] forKey:@"faceuserid"];
                    [personalImformation setObject:[NSString stringWithFormat:@"%@",[re_data objectForKey:@"facetype"]] forKey:@"facetype"];
                   
                    
                    NSMutableDictionary * userinfo = [[NSMutableDictionary alloc]initWithDictionary: [personalImformation objectForKey:@"userinfo"]];
                    [userinfo setObject:[NSString stringWithFormat:@"%d",[[re_data objectForKey:@"faceuserid"] intValue]] forKey:@"faceuserid"];
                    [userinfo setObject:[NSString stringWithFormat:@"%@",[re_data  objectForKey:@"facetype"]] forKey:@"facetype"];
                    
                    NSString *scid = [[re_data objectForKey:@"scid"] stringValue];
                    [personalImformation setObject:scid forKey:@"scid"];
                    
                    [SyUserInfomation personalImformationSaveWtih:personalImformation];
                }
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"switchrolenoti" object:nil userInfo:nil];
                
                [self judgeLoginState];
                
                
            }else {
                [self logOut];
            }
            
        }failure:^(NSInteger recode, NSError *error) {
            [self logOut];
        }];
        
    } failure:^(NSInteger recode, NSError *error) {
        [self logOut];
    }];
    
}

-(void)relogin{
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    
    NSString *userMobile = [SYAccountTool ShareAccount].account.mobile;
    NSString *password = [SYAccountTool ShareAccount].account.loginpass;
    
    [dict setObject:@"api_user_login" forKey:@"method"];
    [dict setObject:userMobile forKey:@"loginname"];
    [dict setObject:password forKey:@"userpass"];

    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        
        NSDictionary * dict = (NSDictionary *)resposeJson;
        
        //判断是否开通平安家校
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:USERID forKey:@"userid"];
        [Utils Java_get:@"api/isOpenFace" parameters:param success:^(NSInteger recode, id jsonObject) {
            
            NSDictionary *jsonDict = (NSDictionary *)jsonObject;
            NSDictionary *re_data=[jsonDict objectForKey:@"re_data"];
            
            if ([[re_data objectForKey:@"openface"] integerValue] == 1) {
                
                NSMutableDictionary *personalImformation = [[NSMutableDictionary alloc]initWithDictionary: [dict objectForKey:@"re_data"]];
                if (personalImformation.count>0) {
                    
                    [personalImformation setObject:[NSString stringWithFormat:@"%d",[[re_data objectForKey:@"faceuserid"] intValue]] forKey:@"faceuserid"];
                    [personalImformation setObject:[NSString stringWithFormat:@"%@",[re_data objectForKey:@"facetype"]] forKey:@"facetype"];
                    
                    NSMutableDictionary * userinfo = [[NSMutableDictionary alloc]initWithDictionary: [personalImformation objectForKey:@"userinfo"]];
                    [userinfo setObject:[NSString stringWithFormat:@"%d",[[re_data objectForKey:@"faceuserid"] intValue]] forKey:@"faceuserid"];
                    [userinfo setObject:[NSString stringWithFormat:@"%@",[re_data objectForKey:@"facetype"]] forKey:@"facetype"];
                   
                    NSString *scid = [[re_data objectForKey:@"scid"] stringValue];
                    [personalImformation setObject:scid forKey:@"scid"];
                    
                    [SyUserInfomation personalImformationSaveWtih:personalImformation];
                }
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"switchrolenoti" object:nil userInfo:nil];
                
                [self judgeLoginState];
                
                
            }else {
                [self logOut];
            }
            
        }failure:^(NSInteger recode, NSError *error) {
            [self logOut];
        }];
        
    } failure:^(NSInteger recode, NSError * error){
        [self logOut];
        
    }];
    
}

- (void)logOut {
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_user_logout" forKey:@"method"];
    [dict setObject:USERID forKey:@"userid"];
    if (lasttype) {
        
        [dict setObject:lasttype forKey:@"usertype"];
    }
    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        

    } failure:^(NSInteger recode, NSError * error){
        
    }];
    
    NSUserDefaults *udd=[NSUserDefaults standardUserDefaults];
    [udd removeObjectForKey:@"studentID"];
    [udd removeObjectForKey:SYStudentName];
    [udd removeObjectForKey:@"userid"];
    [udd synchronize];
    AppDelegate * appdelegate = CONSTAPPDELEGATE;
    appdelegate.studentId = nil;
    appdelegate.myClasses = nil;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

-(void)VersionButton{
    
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:@"1" forKey:@"type"];
    
    [Utils Java_get:@"" parameters:param success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dic = [jsonObject objectForKey:@"re_data"];
        
        if ([dic isKindOfClass:[NSNull class]]) {
            
            return;
        }
        
        if (dic.allValues.count > 0) {
            
            NSString *newVersion = [dic objectForKey:@"version"]; //新版本
            
            NSString *localVersion = [[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleVersion"];
            
            int versiontype = [[dic objectForKey:@"versiontype"] intValue];
            int type = [[dic objectForKey:@"type"] intValue];
            
            if (type == 1 && versiontype == 1) {
                
                if ([localVersion integerValue] < [newVersion integerValue]) {
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"新版本已发布,请更新后使用" delegate:self cancelButtonTitle:nil otherButtonTitles:@"马上更新", nil];
                    
                    alert.tag = 1001;
                    
                    [alert show];
                    
                }
                
            }else{
                
                return;
            }
            
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
 
}


@end
